<template>
  <div class="table-default creatClass">
    <el-button class="backBtn" type="primary" @click="goback" v-if="props.title != '供货商送货单-修改'">返回</el-button>
    <h2>{{ props.title }}</h2>

    <div class="btnRow">
    </div>
    <el-form :model="remarkForm" label-width="100px" ref="form" v-loading="loading">
      <el-form-item label="备注" prop="remarks">
        <div class="formItem">
          <el-input v-model="remarkForm.remarks" name="remarks" clearable width="100" />
          <el-button type="primary" @click="dialogTableVisible = true" class="choseBtn" v-if="!haveID">选择采购订单 </el-button>
          <div class="flex justify-end">
            <el-button type="warning" @click="editSubmit" style="margin-left: 20px" v-if="haveID">提交修改</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="detailscheck_all">
        <el-dialog v-model="dialogTableVisible" title="选择采购订单"  width="70%" height="60vh">
          <openPurchase @send-data="getData" ></openPurchase>
        </el-dialog>
      </el-form-item>

      <!-- {{ tableForm.tableData }} -->
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="供货商送货明细" name="purchase">
          <el-form :model="tableForm" label-width="100px" :rules="rules" ref="ruleFormRef">
            <el-table :data="tableForm.tableData" border>
              <el-table-column prop="fbillno" label="采购订单" min-width="250" fixed="left" />
              <el-table-column prop="fsupplierid_number" label="供应商送编码" min-width="200" />
              <el-table-column prop="fsupplierid_name" label="供应商名称" min-width="200" />
              <el-table-column prop="fprovidercontactid" label="联系人" min-width="200" />
              <el-table-column prop="fproviderphone" label="联系电话" min-width="200" />
              <el-table-column prop="fentryid" label="采购序号" min-width="150" />
              <el-table-column prop="fmaterialid" label="品号" min-width="150" />
              <el-table-column prop="fmaterialname" label="品名" min-width="300" />
              <el-table-column prop="fmaterialmodel" label="规格" min-width="150" />
              <el-table-column prop="fmodel" label="型号" min-width="150" />
              <el-table-column prop="funitid_name" label="单位" min-width="80" />

              <el-table-column prop="quantity" label="数量" width="80" >
                <template #default="scope">
                  {{ Number(scope.row.quantity) }}
                </template>
              </el-table-column>
              <el-table-column prop="thequantity" label="送货数量" width="200" >
                <template #default="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.thequantity'" :rules="rules.thequantity">
                    <el-input-number v-model="scope.row.thequantity" :min="0" />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="number" label="箱数" min-width="180" >
                <template #default="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.number'" :rules="rules.number">
                    <!-- <span class="required">*</span> -->
                    <el-input-number v-model="scope.row.number" :min="0" />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="deliverydate" label="交货日期" width="270" fixed="right">
                <template #default="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.deliverydate'" :rules="rules.deliverydate">
                    <span class="required">*</span>
                    <el-date-picker v-model="scope.row.deliverydate" type="date" placeholder="选择送货日期" :size="size" />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>



<script lang="ts" setup>
import { ref, reactive, onUpdated, watch } from 'vue'
import { useCreate } from '/admin/composables/curd/useCreate'
import { useShow } from '/admin/composables/curd/useShow'
import { onMounted } from 'vue'
import openPurchase from './openPurchase.vue'
import http from '/admin/support/http'
import { useRouter, useRoute } from 'vue-router'
import categoryTable from './categoryTable.vue'
import { ElMessage } from 'element-plus'
import storage from '/admin/utils/storage'

const router = useRouter()
const route = useRoute()

const props = defineProps({
  primary: String | Number,
  api: String,
  supplierId: Number,
  title: String,
  tableData: Object,
})

const haveID = ref(route.query.id)

// const tableData = ref([])
const supplierId = ref()
const newSupplierId = ref()
const categoryShow = ref(false)
const remarkForm = reactive({
  remarks: '',
})

supplierId.value = props.supplierId || newSupplierId.value

let tableForm = reactive({
  tableData: [],
})

if (props.tableData) {
  remarkForm.remarks = props.tableData.remarks
  tableForm.tableData = props.tableData.detailscheck_all
} else {
  remarkForm.remarks = ''
  tableForm.tableData = []
}

console.log('明细表格数据：', tableForm.tableData)

const { formData, form, loading, submitForm, close } = useCreate(props.api, props.primary)
console.log(formData)

const activeName = ref('purchase')

if (props.primary) {
  useShow(props.api, props.primary, formData)
}

const dialogTableVisible = ref(false)

let Data = reactive({
  arr: [],
})

let allArr = reactive([])
let finished = ref(true)
// const tableData = ref([])

const ruleFormRef = ref()

const rules = reactive({
  thequantity: [{ required: true, trigger: 'blur', message: '不能为空' }],
  number: [{ required: true, message: '不能为空', trigger: 'blur' }],
  deliverydate: [{ required: true, message: '不能为空', trigger: 'change' }],
})

let getData = data => {
  dialogTableVisible.value = false

  tableForm.tableData = data.map(item =>{
    return {
      ...item,
      quantity:item.fqty,
      thequantity:item.fqty
    }
  })

  console.log('父组件接受的采购订单数据', data)

  

  // tableForm.tableData = data

  // 重新选择
  console.log(tableForm.tableData)
}



let flag = ref(false)

const CategoryList = ref([])


let FormObj = ref({ remarks: ' ', detailscheck_all: [] })

// 添加送货单，获取新ID，生成新品名
const addSupplier = async formEl => {
  console.log('点击添加', tableForm.tableData)

  if (tableForm.tableData.length == 0) {
    ElMessage.warning('请先选择采购订单！')
  } else {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        for (let i = 0; i < tableForm.tableData.length; i++) {
          let obj = {}
          obj.purchaseorder_id = tableForm.tableData[i].purchaseorder_id
          obj.purchaseorderschedule_id = tableForm.tableData[i].id
          obj.quantity = tableForm.tableData[i].quantity
          obj.deliverydate = tableForm.tableData[i].deliverydate
          obj.thequantity = tableForm.tableData[i].thequantity
          obj.number = tableForm.tableData[i].number
          FormObj.value.detailscheck_all[i] = obj
        }
        console.log(remarkForm.remarks)

        FormObj.value.remarks = remarkForm.remarks
        console.log('品名请求数据', FormObj.value)

        // 新增请求，获取送货单id
        http.post('/purchasing/supplier', FormObj.value).then(r => {
          console.log('新增请求返回数据：', r.data)
          haveID.value = r.data.data
          ElMessage({
            message: r.data.message,
            type: 'success',
          })

          // 新增成功，切换到详情页
          router.push(`/purchasing/supplierDetail?id=${haveID.value}`)
        })

        // categoryShow.value = true // // 确保 暂收数量等input不为空，不然无法新增的
      } else {
        ElMessage({
          message: '有未输入文本！',
          type: 'warning',
        })
      }
    })
  }
}

// // 新增成功返回id,生成品名列表
// const createCategory = () => {
//   getCategoryApi(newSupplierId.value)
//   console.log(CategoryList.value)
// }

const editForm = ref({})

const forTypebox = (row, column, value, index) => {
  return {
    0: '混合装',
    1: '整箱装',
  }[value]
}

// const numberChange = val => {
//   console.log(val)
//   console.log(CategoryList)
//   let flag = false
//   let arr = []

//   CategoryList.value.forEach((item, index) => {
//     console.log(!item.number)
//     if (!item.number) {
//       flag = true
//     }
//     arr[index] = {}
//     arr[index].purchaseorderschedule_id = item.id
//     arr[index].number = item.number
//   })
//   if (flag) {
//     // console.log('有未填的');
//     finished.value = true
//   } else {
//     console.log(arr)
//     // console.log('填完了');
//     finished.value = false
//   }
//   FormObj.value.id = Number(supplierId.value)
//   FormObj.value.SuppliernamedeliveryAll = arr
//   console.log(FormObj.value)
// }

// watch(FormObj.value, (newVal, oldVal) => {
//   // 当 formData 改变时触发
//   newVal == oldVal ? finished.value = false : finished.value = true
// })

const editSubmit = () => {
  console.log('提交修改：', FormObj.value)

  // 确认修改，需要参数
  // 获取FormObj，在FormObj的基础上在拼接SuppliernamedeliveryAll：['purchaseorderschedule_id':'',number:'']
  // http.put(`/purchasing/supplier/${Number(supplierId.value)}`, FormObj.value).then(r => {
  //   let res = r.data
  //   console.log('确认修改请求返回：', res)

  //   ElMessage({
  //     message: r.data.message,
  //     type: 'success',
  //   })
  // })
}

// 删除
const delHandler = index => {
  console.log(index)
  tableForm.tableData.splice(index, 1)
  ElMessage.info('删除后不要忘记提交修改哦~')
  finished.value = true
}

// // 返回，切换组件
// const goback = () => {
//   router.push('/purchasing/supplier')
// }

let emit = defineEmits(['send-data'])

const goback = () => {
  emit('send-data')
  router.push('/purchasing/supplier')
}

onUpdated(() => {
  console.log(allArr)
  console.log(formData.value)
})
</script>

<style>
.btnRow {
  margin: 20px;
}
h2 {
  /* margin-left: 10px; */
  text-align: left;
  font-weight: bold;
}
/* .creatClass {
  padding: 0 60px 20px 0;
} */
.formItem {
  display: flex;
  /* justify-content: space-between; */
}

.choseBtn {
  margin: 0 50px;
}
.required {
  transform: translateY(-100px);
  color: red;
}
.demo-tabs {
  margin: 20px 0px 20px 20px;
}
.backBtn {
  margin: 20px 10px;
}
.el-form-item__content {
  margin-left: 0 !important;
}

</style>
